/**
 * Created by liubin on 2014/09/02.
 */
define(['angular', 'controllers', 'user/userService'], function(angular, controllers){
    'use strict';
    controllers.controller('userListCtrl', ['$scope', '$location', '$window', 'DTOptionsBuilder','DTColumnBuilder',
     'userListService', 'userService', 'alertModalService', 'spinModalService', 'pageSize', 'actionColumnTemplate',
    function($scope, $location, $window, DTOptionsBuilder, DTColumnBuilder, userListService, userService,
             alertModalService, spinModalService, pageSize, actionColumnTemplate){
        $scope.table = null;
        $scope.dtOptions = DTOptionsBuilder.newOptions().
            withOption('dom',
            // 追加按钮行
            '<"toolbar">frtip').
            withOption('ajax', function(data, callback, settings){
                console.log(data);
                console.log(callback);
                console.log(settings);
                // 数据读取
                var users = [];
                userListService.get(
                    {
                        draw: data.draw,
                        size: pageSize,
                        start: data.start,
                        // 查询
                        query: $scope.query
                    },
                    {},  function (result){
                    angular.forEach(result.data, function (value, key) {
                        value.op = '';
                        users.push(value);
                    });
                    //users =
                    console.log(result);
                    callback({
                        draw: result.draw,
                        data: users,
                        recordsTotal: result.total,
                        recordsFiltered: result.total
                    });
                });
                //todo: add user get failure
            }).
            withOption('rowCallback', function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                // 增加按钮事件
                console.log(aData);
                //console.log($('a[action]', nRow));
                // 查看详细
                $('a[action=view]', nRow).bind('click', function(){
                    $scope.$apply(function() {
                        $scope.view(aData);
                    });
                });
                // 删除
                $('a[action=delete]', nRow).bind('click', function(){
                    $scope.$apply(function() {
                        $scope.delete(aData);
                    });
                });
                return nRow;
            }).
            withDataProp('data').
            withPaginationType('full_numbers');
        $scope.handleSearch = function(e){
            if (e.which === 13) {
                console.log('Search!!!');
                if($scope.table){
                    console.log('DoSearch!!!');
                    $scope.table.DataTable().ajax.reload();
                }
            }
        };
        $scope.$on('event:dataTableLoaded', function(event, loadedDT) {

            // 追加按钮
            $("div.toolbar").html('<a class="btn col-sm-1 btn-danger" href="' + urlRoute.getUrl('user_add')
                + '" style="margin:0px 0px 3px 0px">新增</a>');
            // 宽度自适应
            var table = $("#" + loadedDT.id);
            $scope.table = table;
            $(window).resize(function(){
                table.attr('style',{'width': ''});
            });

        });
        $scope.dtColumns = [
            DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
            DTColumnBuilder.newColumn('name').withTitle('用户名'),
            DTColumnBuilder.newColumn('real_name').withTitle('姓名'),
            DTColumnBuilder.newColumn('op').withTitle('操作').renderWith(
                function(){
                    return actionColumnTemplate;
                }
            )
        ];
        $scope.view = function(data){
            console.log('view');
            console.log(data);
            var id = data.id;
            console.log(urlRoute.getUrl('user_view')+ '/' + id);
            $location.url(urlRoute.getUrl('user_view')+ '/' + id);
        }
        $scope.delete = function(data){
            console.log('delete');
            console.log(data);
            // 弹出框
            // 参数: 标题，内容，回调函数
            alertModalService.open('confirm', '确认', '你是否要删除该用户？', function(){
                console.log('do delete');
                spinModalService.open();
                userService.delete({id: data.id}, {},
                function(success){
                    if (success.success) {
                        $window.location.href = urlRoute.getUrl('user_list');
                    }
                    else{
                        console.log(success.messages);
                        alertModalService.open('alert', '错误', success.messages[0]);
                    }
                    spinModalService.close();
                },
                function(error){
                    console.log('error');
                    alertModalService.open('alert', '错误', '服务器发生错误!');
                    spinModalService.close();
                });
            });
        }
    }]).controller('userAddCtrl', ['$scope', '$window', 'userListService', 'alertService', 'spinModalService',
        function($scope, $window, userListService, alertService, spinModalService){
            $scope.add = function(e){
            console.log('add');
            console.log($scope.user);
            alertService.init($scope);

            if($scope.user.pwd != $scope.user.repeat_pwd){
                alertService.addAlert({
                    msg:  '俩次密码输入不一致',
                    type: 'danger'
                    //danger: true
                });
                return;
            }
            spinModalService.open();
            userListService.post(
                // get 参数
                {},
                // post参数
                {
                    name: $scope.user.name,
                    real_name: $scope.user.real_name,
                    pwd: $scope.user.pwd
                },
                function (success) {
                    console.log(success);
                    if (success.success) {
                        $window.location.href = urlRoute.getUrl('user_list');
                    }
                    else{
                        console.log(success.messages);
                        angular.forEach(success.messages, function (value, key) {
                            alertService.addAlert({
                                msg:  value,
                                type: 'danger'
                                //danger: true
                            });
                        });
                    }
                    spinModalService.close();
                },
                function (error) {
                    //todo: add user get failure
                    console.log('error');
                    spinModalService.close();
                }
            );
        }
    }]).controller('userViewCtrl', ['$scope', '$routeParams', '$q', '$location', 'userService', 'alertService', 'spinModalService',
        function($scope, $routeParams, $q, $location, userService, alertService, spinModalService){
        console.log('view');
        console.log($routeParams.id);
        $scope.security = {};
        $scope.tabs = {
            first : true
        };
        var saveUser = function(data){
            console.log('saveUser');
            console.log(data);
            var d = $q.defer();
            userService.put(
                {id: $routeParams.id},
                data,
                function (success) {
                    console.log(success);
                    if (success.success) {
                        d.resolve();
                    }
                    else{
                        var message = [];
                        angular.forEach(success.messages, function (value, key) {
                            message.push(value);
                        });
                        if(message){
                            d.resolve(message[0]);
                        }
                        else{
                            d.resolve('服务器错误!');
                        }
                    }
                },
                function(error){
                    console.log(error);
                    d.resolve('服务器错误!');
                }
            );
            return d.promise;
        }
        userService.get(
            {id: $routeParams.id},
            {},
            function (success) {
                console.log(success);
                if (success.success) {
                    console.log(success.data);
                    $scope.user = success.data;
                    //$scope.getCompleted = true;
                }
                else {
                    //todo: add user get failure
                }
            }
        );
        $scope.updateRealName = function(real_name){
            if(!real_name){
                return '姓名不能为空!'
            }
            else{
                var data = angular.copy($scope.user);
                data.real_name = real_name;
                return saveUser(data);
            }
        };
        $scope.updatePwd = function(e){
            alertService.init($scope);
            if($scope.security.pwd != $scope.security.repeat_pwd){
                alertService.addAlert({
                    msg:  '俩次密码输入不一致',
                    type: 'danger'
                    //danger: true
                });
                return;
            }
            spinModalService.open();
            // 利用post做密码更新
            userService.post(
                {id: $routeParams.id},
                {
                    pwd:$scope.security.pwd
                },
                function (success) {
                    console.log(success);
                    if (success.success) {
                        console.log(success);
                        $scope.security = {};
                        $scope.tabs.first = true;
                        //$location.url(urlRoute.getUrl('user_view')+ '/' + $routeParams.id);
                    }
                    else{
                        var message = [];
                        angular.forEach(success.messages, function (value, key) {
                            alertService.addAlert({
                                msg:  value,
                                type: 'danger'
                                //danger: true
                            });
                        });

                    }
                    spinModalService.close();
                },
                function(error){
                    console.log(error);
                    alertService.addAlert({
                        msg:  '服务器错误',
                        type: 'danger'
                        //danger: true
                    });
                    spinModalService.close();
                }
            );
        }
    }]);
});